# -*- encoding: utf-8 -*-

"""
@File:      tc_readline_fun_001.py
@Time:      2024-02-27 16:30:00
@Author:    qintingting
@Version:   1.0
@Contact:   wb-qtt862918@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    qintingting
"""
import pexpect
from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_readline_fun_001.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "readline readline-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline='''cat > readline_fun_001.c <<EOF
#include <stdio.h>
#include <stdlib.h> 
#include <readline/readline.h>
#include <readline/history.h>

int main() {
    char* input;

    while (1) {
        input = readline("Enter command: ");
        if (input == NULL || strcmp(input, "exit") == 0) {
            break;
        }
        printf("You entered: %s\\n", input);
        add_history(input);
        free(input);
    }

    return 0;
}
EOF
'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o readline_fun_001 readline_fun_001.c -lreadline")
        code, result = self.cmd("file readline_fun_001")
        self.assertIn("executable", result)
        child = pexpect.spawnu('./readline_fun_001')
        total_output = ""
        
        #Check command-line interaction
        for line in ['Hello World', 'Another Line']:
            child.sendline(line)
            child.expect('You entered: ' + line)
            total_output += child.before.strip() + "\n"
      
        child.sendline('exit')
        child.expect(pexpect.EOF)
        child.close()
     
        # confirm exit status
        if child.exitstatus == 0:
            print('Program exited successfully.')
        else:
            print('Program did not exit successfully.')
       
        #Check buffer interaction content
        total_output += child.before.strip()
        print("Output during interaction:\n", total_output)
        for line in ['Hello World', 'Another Line','exit']:
            self.assertIn(line,total_output)
            
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf readline_fun_001 readline_fun_001.c")